#include "Log.hpp"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
class Sock
{
    const int defaultfd = -1;

public:
    int Socket()
    {
        int fd = socket(AF_INET, SOCK_STREAM, 0);
        if (fd == -1)
        {
            logMessage(ERROR, "socket创建失败");
            exit(SOCK_ERR);
        }
        logMessage(NORMAL, "socket创建成功");
        int opt = 1;
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        return fd;
    }
    void Bind(int fd, int port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = INADDR_ANY;
        int ret = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
        if (ret == -1)
        {
            logMessage(ERROR, "bind失败");
            exit(BIND_ERR);
        }
        logMessage(NORMAL, "bind成功");
    }
    void Listen(int fd)
    {
        int ret = listen(fd, 16);
        if (ret == -1)
        {
            logMessage(ERROR, "listen失败");
            exit(LISTEN_ERR);
        }
        logMessage(NORMAL, "listen成功");
    }
    int Accept(int fd, int &err)
    {
        struct sockaddr_in addr;
        socklen_t len = sizeof(addr);
        int sock = accept(fd, (struct sockaddr *)&addr, &len);
        err = errno;
        if (sock == -1)
        {
            logMessage(ERROR, "accept失败");
            return -1;
        }
        int port = ntohs(addr.sin_port);
        string ip = inet_ntoa(addr.sin_addr);
        logMessage(NORMAL, "accept成功 : [%d][%s][%d]", sock, ip.c_str(), port);
        return sock;
    }
};